import React, { useState, FC, useRef } from 'react';
import { Table, Button, Space, Popconfirm, Pagination, message } from 'antd';
import ProTable, { ProColumns, TableDropdown } from '@ant-design/pro-table';
import { connect, Dispatch, Loading, UserState } from 'umi';
import UserModal from './components/UserModal';
import { SingleUserType, FormValues } from './data.d';
import { getRemoteList, editRecord, addRecord, deleteRecord } from './service';

interface UserPageProps {
  users: UserState;
  dispatch: Dispatch;
  userListLoading: boolean;
}

// 和request 刷新按钮有关
// interface ActionType {
//   reload: () => void;
//   fetchMore: () => void;
//   reset: () => void;
// }

const UserPageList: FC<UserPageProps> = ({
  users,
  dispatch,
  userListLoading,
}) => {
  const [modalVisible, setIsModalVisible] = useState(false);
  const [confirmLoading, setConfirmLoading] = useState(false);
  const [record, setRecord] = useState<FormValues | undefined>(undefined);
  // const ref = useRef<ActionType>();

  const columns: ProColumns<SingleUserType>[] = [
    {
      title: 'ID',
      dataIndex: 'id',
      valueType: 'digit',
      key: 'id',
    },
    {
      title: 'Name',
      dataIndex: 'name',
      valueType: 'text',
      key: 'name',
      render: (text: any) => <a>{text}</a>,
    },
    {
      title: 'Create Time',
      dataIndex: 'create_time',
      valueType: 'dateTime',
      key: 'create_time',
    },
    {
      title: 'Email',
      dataIndex: 'email',
      valueType: 'text',
      key: 'email',
    },
    {
      title: 'Action',
      key: 'action',
      valueType: 'option',
      render: (text: any, record: SingleUserType) => [
        <a
          onClick={() => {
            editHandler(record);
          }}
        >
          Edit
        </a>,
        <Popconfirm
          title="Are you sure delete this user?"
          onConfirm={() => {
            deleteHandler(record.id);
          }}
          okText="Yes"
          cancelText="No"
        >
          <a>Delete</a>
        </Popconfirm>,
      ],
    },
  ];

  const editHandler = (record: SingleUserType) => {
    setIsModalVisible(true);
    setRecord(record);
  };

  const onFinish = async (values: FormValues) => {
    setConfirmLoading(true);
    let id = 0;

    if (record) {
      id = record.id;
    }

    // if (id) {
    //   dispatch({
    //     type: 'users/edit',
    //     payload: { values, id },
    //   });
    // } else {
    //   dispatch({
    //     type: 'users/add',
    //     payload: { values },
    //   });
    // }

    // setIsModalVisible(false);

    let serviceFun;
    if (id) {
      serviceFun = editRecord;
    } else {
      serviceFun = addRecord;
    }

    const result = await serviceFun({ id, values });
    if (result) {
      setIsModalVisible(false);
      message.success(`${id === 0 ? 'Add' : 'Edit'} Successfully.`);
      resetHandler();
      setConfirmLoading(false);
    } else {
      setConfirmLoading(false);
      message.error(`${id === 0 ? 'Add' : 'Edit'} Failed.`);
    }
  };

  const handleCancel = () => {
    setIsModalVisible(false);
  };

  const deleteHandler = (id: number) => {
    dispatch({
      type: 'users/delete',
      payload: {
        id,
      },
    });
  };

  const addHandler = () => {
    setIsModalVisible(true);
    setRecord(undefined);
  };

  // 用了 antd 分页组件 request 分页参数就会失效
  // const requestHandler = async ({ pageSize, current }) => {
  //   const usersList = await getRemoteList({
  //     page: current,
  //     per_page: pageSize,
  //   });

  //   if (usersList) {
  //     return {
  //       data: usersList.data,
  //       success: true,
  //       total: usersList.meta.total,
  //     };
  //   } else {
  //     return {
  //       data: [],
  //     };
  //   }
  // };

  // 分页按钮
  const paginationHandler = (page: number, pageSize?: number) => {
    dispatch({
      type: 'users/getRemote',
      payload: {
        page,
        per_page: pageSize ? pageSize : users.meta.per_page,
      },
    });
  };

  const pageSizeHandler = (current: number, size: number) => {
    dispatch({
      type: 'users/getRemote',
      payload: {
        page: current,
        per_page: size,
      },
    });
  };

  // 刷新方法是基于request的
  // const reloadHandler = () => {
  //   ref.current.reload();
  // };

  const resetHandler = () => {
    dispatch({
      type: 'users/getRemote',
      payload: {
        page: users.meta.page,
        per_page: users.meta.per_page,
      },
    });
  };

  return (
    <div className="list-table">
      {/* <Button type="primary" onClick={addHandler}>
        Add
      </Button>
      <Button onClick={resetHandler}>Reload</Button> */}
      <ProTable
        columns={columns}
        dataSource={users.data}
        rowKey="id"
        loading={userListLoading}
        // request={requestHandler} request 和 dataSource互斥
        search={false}
        // actionRef={ref}
        pagination={false}
        options={{
          density: true,
          fullScreen: true,
          reload: () => {
            resetHandler();
          },
          setting: true,
        }}
        headerTitle="User List"
        toolBarRender={() => [
          // 在列表里面放button
          <Button type="primary" onClick={addHandler}>
            Add
          </Button>,
          <Button onClick={resetHandler}>Reload</Button>,
        ]}
      />
      <Pagination
        className="list-page"
        total={users.meta.total}
        onChange={paginationHandler}
        onShowSizeChange={pageSizeHandler}
        current={users.meta.page}
        pageSize={users.meta.per_page}
        showSizeChanger
        showQuickJumper
        showTotal={total => `Total ${total} items`}
      />
      <UserModal
        visible={modalVisible}
        onFinish={onFinish}
        handleCancel={handleCancel}
        record={record}
        confirmLoading={confirmLoading}
      ></UserModal>
    </div>
  );
};

// 第一种写法
// const mapStateToProps = ({ users }) => {
//   return {
//     users,
//   };
// };
// export default connect(mapStateToProps)(index);

// 第二种写法
export default connect(
  ({ users, loading }: { users: UserState; loading: Loading }) => ({
    users,
    userListLoading: loading.models.users,
  }),
)(UserPageList);
